<template>
    <el-form :model="baseForm" ref="bsFormRef" label-width="auto" class="dynamic-form">
      <el-form-item label="指令名称">
        <el-input :value="curCmdDict.cmdName" disabled></el-input>
      </el-form-item>
      <el-form-item label="操作码">
        <el-input :value="toHexOpcode(curCmdDict.opcode)" disabled></el-input>
      </el-form-item>
      <template
          v-for="(oneParam, index) in curCmdDict.params"
          :key="index"
      >
        <el-form-item
        v-if="oneParam.type === '可变参数'"
        :label="oneParam.name"
        :prop="'params.' + index"
        :rules="{
         required: true,
          message: '必填',
          trigger: 'blur',
        }"
        >
            <el-select
              v-if="oneParam.process === '状态量十六进制'"
              v-model="baseForm.params[index]" placeholder="Select" style="width: 281px">
              <el-option
                v-for="item in genOptions(oneParam['status'])"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                <span style="float: left">{{ item.label }}</span>
                <span
                  style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "
                  >{{ toHex(item.value) }}</span
                >
              </el-option>
            </el-select>
            <el-input
            v-else
            required
            v-model="baseForm.params[index]"
            :prop="'params.' + index"
            :placeholder="getHolder(curCmdId)"
            :rules="[
              { required: true, message: '必填', trigger: 'blur' },
              { type: 'number', message: '必须是数字', trigger: 'blur', transform: (v) => Number(v) }
              ]"
            ></el-input>
        </el-form-item>
        <el-form-item
        v-if="oneParam.type === '固定参数' && oneParam.process !== '填充'"
        :label="oneParam.name"
        >
            <el-input
            :value="oneParam.content"
            :placeholder="getHolder(curCmdId)"
            :disabled="true"
            ></el-input>
        </el-form-item>
      </template>
      <el-form-item>
        <div class="btn-pos">
            <el-button @click="cancelForm">取消</el-button>
            <el-button class="pry-btn" @click="submitForm">发送</el-button>
        </div>
      </el-form-item>
    </el-form>
</template>

<script setup>
import { ref, computed, onBeforeMount, defineEmits } from 'vue'
import { useTcStore } from '@/stores/tc-module.js'
import { floatToBytes32, signedToBytes16, evalFunc, failedNotify, successNotify,
  hexToBigEndianBytes, decimalToHex } from '@/comm/index.js'
import { setTcCmd } from '@/api/loads-api'

const bsFormRef = ref(null)
const dtcStore = useTcStore()
const curCmdId = computed(() => dtcStore.selCmdId)
const curCmdDict = computed(() => dtcStore.cmdObj[curCmdId.value])
const sendTdForm = computed(() => dtcStore.sendTdForm)

const emit = defineEmits(['close'])

let baseForm = ref({
  cmdName: '',
  id: '',
  params: []
})

// onBeforeMount(() => {
//   console.log("curCmdId.value：",curCmdId)
//   if (sendTdForm.hasOwnProperty(curCmdId) === false) {
//     initForm()
//   }
// })

const initForm = () => {
  if (sendTdForm.value.hasOwnProperty(curCmdId.value) === true) {
    baseForm.value = {...baseForm.value, ...sendTdForm.value[curCmdId.value] }
    //console.log("从store中初始化，baseForm", baseForm.value)
    return false
  }
  //console.log("准备初始化：", curCmdDict.value.params)
  baseForm.value = {
    cmdName: '',
    id: '',
    params: []
  }
  for(let item of curCmdDict.value.params) {
    if (item.type === '固定参数' || item.process.indexOf('无符号') > -1) {
      baseForm.value.params.push(item.content)
    } else {
      baseForm.value.params.push('')
    }
  }
  //console.log("初始化后的baseForm：", baseForm.value)
}

const toHex = (val) => {
  return '0x' + (parseInt(val).toString(16).padStart(2, '0')).toUpperCase()
}

const genOptions = (obj) => {
  let res = []
    for (let key in obj) {
      let tmpObj = {
        'value': key,
        'label': obj[key]
      }
      res.push(tmpObj)
    }
    return res
}

const disposeContent = () => {
  const arrParams = baseForm.value.params
  const tLen = arrParams.length
  let resArr = []
  let processArr = []
  for(let i=0; i < tLen; i++) {
      processArr[i] = curCmdDict.value.params[i].process
      switch(processArr[i]) {
        case '状态量十六进制':
          //resArr[i] = parseInt(arrParams[i])
          resArr.push(parseInt(arrParams[i]))
          break
        case '32单精度浮点':
          const arr = floatToBytes32(arrParams[i])
          resArr = [...resArr, ...arr]
          break
        case '公式十进制':
          const content = curCmdDict.value.params[i].content
          const calRes = evalFunc(content, arrParams[i])
          resArr = [...resArr, ...floatToBytes32(calRes)]
          break
        case '有符号':
          const signedArr = signedToBytes16(arrParams[i], 16)
          resArr = [...resArr, ...signedArr]
          break
        case '无符号4字节':
        case '无符号2字节':
        case '无符号1字节':
          const unsinedArr = hexToBigEndianBytes(arrParams[i], curCmdDict.value.params[i].len)
          resArr = [...resArr, ...unsinedArr]
          break
        case '填充':
        case '十六进制':
          const filledArr = disposeFixedParam(curCmdDict.value.params[i])
          resArr = [...resArr, ...filledArr]
          break
        default:
          break
      }
  }
  return resArr
}

const disposeFixedParam = (paramObj) => {
  let resArr = []
  let len = paramObj.len
  for(let i=0; i < len; i++) {
    resArr.push(parseInt(paramObj.content))
  }
  return resArr
}
const submitForm = () => {
  bsFormRef.value.validate(valid => {
    if(valid) {
      baseForm.value.cmdName = curCmdDict.value.cmdName
      baseForm.value.id = curCmdDict.value.id

      //console.log("提交后的baseForm.value：",baseForm.value)
      let reqJson = { id: baseForm.value.id, cmdName: baseForm.value.cmdName, valueList: [] }
      reqJson.valueList = disposeContent()
      reqJson.valueList.unshift(curCmdDict.value.opcode)

      setTcCmd(reqJson, (response => {
        dtcStore.setSendTdForm(baseForm.value)
        successNotify('指令发送成功')
        closeForm()
      }), (error => {
        dtcStore.setSendTdForm(baseForm.value)
        failedNotify('指令发送失败!', error)
        closeForm()
      }))
    }
  })  
}
const getHolder = (id) => {
  const hodlerDict = {
    'K002': '请输入-3.4E38～3.4E38之间的浮点数',
    'K004': '请输入一个正数',
    'K005': '请输入-32768～32767之间的整数'
  }

  return hodlerDict[id]
}

const resetForm = () => {
  baseForm.value.cmdName = ''
  baseForm.value.id = ''
  baseForm.value.params = []
}

const closeForm = () => {
  emit('close')
}

const cancelForm = () => {
  dtcStore.clearSendTdForm(curCmdId.value)
  resetForm()
  emit('close')
}
const  toHexOpcode = (value) => {
  return '0x' + decimalToHex(value)
}
defineExpose({
  initForm,
  resetForm
})

</script>

<style lang="scss" scoped>
.dynamic-form {
  width: 350px;
}
.dynamic-form .el-select {
  width: 100%;
}
.btn-pos {
  margin-left: 30%;
}
</style>